package com.wiz.netty.service;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wiz.common.util.ByteUtil;
import com.wiz.common.util.KeyUtil;
import com.wiz.data.vo.to.DataMessageTemplate;
import com.wiz.data.vo.to.MabDataTO;
import com.wiz.log.NettyInfoRecord;
import com.wiz.netty.NettyXmlParseFactory;
import com.wiz.netty.message.NettyMessageFactory;
import com.wiz.netty.message.NettyMessageTO;
import com.wiz.web.manager.ServiceManager;
import com.wiz.web.service.LoginService;
import com.wiz.web.vo.type.ServiceType;

/**
 * 签到处理线程
 * @author Hakeny
 */
public class NettyLoginThread extends NettyThread implements Runnable {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	public NettyLoginThread(ChannelHandlerContext ctx,NettyMessageTO.MessageContent message,
			ServiceManager serviceManager,NettyXmlParseFactory wizXmlFactory){
		this.ctx = ctx;
		this.message = message;
		this.serviceManager = serviceManager;
		this.wizXmlFactory = wizXmlFactory;
	}
	
	@Override
	public void run() {
		try {
			//验证密钥
			boolean b = this.checkStaticMac(message.getMac().toByteArray(), message.getIden().toStringUtf8());
			if(b){
				//返回动态密钥，绑定站点关系
				LoginService loginService = (LoginService) serviceManager.getService(ServiceType.LOGIN.getId());
				String dynamicKey = KeyUtil.resetDynamicKey();
				loginService.setDynamicKey(message.getIden().toStringUtf8(), dynamicKey);
				//下放动态密钥
				MabDataTO mabDataTO = new MabDataTO();
				mabDataTO.setWiz_64_dynakey(dynamicKey);
				DataMessageTemplate dm = wizXmlFactory.getDataMessageTemplate("dynanicKey");
				byte[] mti = messageDataFactory.getMtiMessage(dm);
				byte[] mab = messageDataFactory.getMabMessage(mabDataTO, dm);
				byte[] key = dynamicKey.getBytes();
				byte[] mac = messageDataFactory.getMac("00010001".getBytes(), key);//下发动态密钥特殊mac
				ctx.writeAndFlush(NettyMessageFactory.getInstance().getSignMessage(mti, mab, mac));
				NettyInfoRecord.infoRecord(message.getIden().toStringUtf8()+" login success,sended dyncatic key");
			}else{
				NettyInfoRecord.warnRecord("the LoginMessage mac="+ByteUtil.Bytes2HexString(message.getMac().toByteArray())+
						" from "+message.getIden().toStringUtf8()+" happen mac error");
			}
		} catch (Exception e) {
			log.error("send dynadic Key fail",e);
		}
	}

}
